package controllers

import (
	"github.com/astaxie/beego"
	"github.com/xuxusheng/beego-learn/models"
	"log"
	"encoding/xml"
	"time"
)

type MainController struct {
	beego.Controller
}

type WxMessage struct {
	ToUserName string
}

func (c *MainController) Prepare() {

	models.LogRequest(&c.Controller)

	ok := authSignature(&c.Controller)
	if !ok {
		c.Ctx.WriteString("sorry, signature is invalid!")
	}
}

func (c *MainController) Post() {

	// 提取消息
	contentType := c.Ctx.Input.Header("content-type")

	switch contentType {
	case "text/xml":
		// 提取
		msg, err := models.ExtractMsg(c.Ctx.Input.RequestBody)
		if err != nil {
			log.Printf("extract message error: %s", err)
			return
		}

		log.Printf("message is: %s", msg)
		/*		c.Ctx.Output.XML(models.Message{
					ToUserName:   msg.FromUserName,
					FromUserName: msg.ToUserName,
					CreateTime:   time.Now().Unix(),
					MsgType:      msg.MsgType,
					Content:      msg.Content,
				}, false)*/

		reply, err := xml.Marshal(models.Message{
			ToUserName:   msg.FromUserName,
			FromUserName: msg.ToUserName,
			CreateTime:   time.Now().Unix(),
			MsgType:      msg.MsgType,
			Content:      msg.Content,
		})

		c.Ctx.Output.ContentType(contentType)
		c.Ctx.Output.Body(reply)

	}

	c.Ctx.WriteString("success")
}
